package com.jasiri.project.pro

import android.view.View
import com.jasiri.project.R
import com.jasiri.project.base.BaseActivity
import com.jasiri.project.ui.permission.PermitUtil
import com.jasiri.project.ui.user.activity.FeedbackActivity
import com.jasiri.project.ui.user.activity.UserLoginActivity
import com.jasiri.project.utils.config.Configs
import com.jasiri.project.utils.dialog.DataClearDialog
import com.jasiri.project.utils.dialog.KefuDialog
import com.jasiri.project.utils.dialog.PersonalDialog
import com.jasiri.project.utils.helper.StarDialogHelper
import com.jasiri.project.utils.http.AppUrls
import com.jasiri.project.utils.http.AppUrls.addCommonParams
import com.jasiri.project.utils.http.HttpHelper
import com.jasiri.project.utils.http.IHttpCallback
import com.jasiri.project.utils.log.HHLog
import com.jasiri.project.utils.sp.SPUtils
import org.json.JSONObject
import java.io.File

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/20 16:10
 * @Annotation：
 */
abstract class ProActivity: BaseActivity() {

    //是否需要隐藏加载框
    var isNeedHideLoading = true
    var mKefuDialog: KefuDialog? = null//客服
    var personalDialog: PersonalDialog? = null//个人中心

    /**
     * 获取APP配置信息
     */
    fun getCommonObject(): JSONObject{
        return JSONObject(Configs.getSPString(Configs.SPKEY.JASIRI_COMMON))
    }

    /**
     * 显示客服dialog
     */
    fun showKefuDialog(eventRemark: String){
        mKefuDialog?.let {
            if (it.isShowing){
                return
            }
        }
        if (mKefuDialog == null){
            mKefuDialog = KefuDialog(this,eventRemark,object : KefuDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.btnKefuFeedback){
                        onIntent(FeedbackActivity::class.java)
                    }
                }
            })
            mKefuDialog?.setCancelable(true)
            mKefuDialog?.setCanceledOnTouchOutside(false)
            mKefuDialog?.show()
            mKefuDialog?.loadKefuContactAction()
            return
        }
        mKefuDialog?.show()
    }

    /**
     * 显示个人中心dialiog
     */
    fun showPersonalDialog(eventRemark: String){
        personalDialog?.let {
            if (it.isShowing){
                return
            }
        }
        if (personalDialog == null){
            personalDialog = PersonalDialog(this,eventRemark,object : PersonalDialog.IDialogCallback{
                /**
                 * 打分
                 */
                override fun onRateUsClick() {
                    loadSikadwaRateUsAction()
                }

                /**
                 * 清除用户数据
                 */
                override fun onSikadwaDataClearClick() {
                    showSikadwaDataClearConfirmDialog(eventRemark)
                }

                /**
                 * 退出登录
                 */
                override fun onSikadwaLoginOutClick() {
                    onLoginOutAction()
                }
            })
        }
        personalDialog?.show()
        loadSikadwaUserDataClearAction(true)
    }

    /**
     * 是否确认清除用户数据dialog
     */
    fun showSikadwaDataClearConfirmDialog(eventRemark: String){
        val dialog = DataClearDialog(this,eventRemark,object : DataClearDialog.IDialogCallback{
            override fun onClick(view: View?) {
                showLoading()
                loadSikadwaUserDataClearAction(false)
            }
        })
        dialog.show()
    }

    /**
     * 退出登录
     */
    fun onLoginOutAction(){
        //清除权限状态
        PermitUtil.resetAllPermitOperated(SPUtils.getAppSp())
        //移除已登录状态
        SPUtils.remove(Configs.SPKEY.JASIRI_LOGIN)
        //移除用户Token
        SPUtils.remove(Configs.SPKEY.JASIRI_TOKEN)
        //移除用户id
        SPUtils.remove(Configs.SPKEY.JASIRI_USERID)
        SPUtils.remove(Configs.SPKEY.JASIRI_MOBILE)
        SPUtils.remove(Configs.SPKEY.JASIRI_IS_ADSOURCE)
        SPUtils.remove(Configs.SPKEY.JASIRI_PROCESS)
        SPUtils.remove(Configs.SPKEY.JASIRI_PERMISSION_REASON_STATUS)

        onIntent(UserLoginActivity::class.java)
    }

    /**
     * 开始网络请求 Post
     * @param url       : 接口地址
     * @param params    : 参数
     * @param callback  :  回调
     */
    open fun postAction(url: String, params: JSONObject, callback: IHttpCallback) {
        HttpHelper.post(url, params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val code = data.optInt("code")
                when(code){
                    0 -> {//成功
                        callback.onRequestSuccess(data)
                    }
                    else -> {//失败
                        val msg = data.optString("msg")
                        showToast(msg)

                        callback.onRequestError(data)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                callback.onRequestError(error)
                HHLog.e("error：${params.optString("path")}-->$error")
                showToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                callback.onRequestFinish()
                if (isNeedHideLoading){
                    hideLoading()
                }
            }
        })
    }

    /**
     * POST方式请求 (文件上传)
     *
     * @param url
     * @param file
     * @param callback
     */
    open fun uploadFileAction(url: String, file: File, callback: IHttpCallback){
        HttpHelper.uploadFile(url,file,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val code = data.optInt("code")
                when(code){
                    0 -> {//成功
                        callback.onRequestSuccess(data)
                    }
                    else -> {//失败
                        val msg = data.optString("msg")
                        showToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                HHLog.e("error：$error")
                showToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                callback.onRequestFinish()
                if (isNeedHideLoading){
                    hideLoading()
                }
            }
        })
    }

    /**
     * 打分
     */
    private fun loadSikadwaRateUsAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.STAR_COMMENT)
        }
        postAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                StarDialogHelper.showStarDialog(this@ProActivity,obj,false)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取是否显示删除用户数据按钮
     */
    private fun loadSikadwaUserDataClearAction(isGetBtn: Boolean){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.USER_DATA_CLEAR)
        }
        if (isGetBtn){
            params.put("type","GET")
        } else {
            params.put("type","DROP")
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                if (isGetBtn){
                    val obj = data.optJSONObject("obj")
                    if (obj != null){
                        val showDropButton = obj.optString("showDropButton","NO")
                        personalDialog?.showSikadwaDataClearButtonVisibility(showDropButton == "YES")
                    }
                } else {
                    hideLoading()
                    //退出登录，需要移除用户保存的信息
                    onLoginOutAction()
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideLoading()
            }
        })
    }

    /**
     * 添加埋点
     */
    open fun addEvent(eventName: String,remark: String? = ""){
        HttpHelper.addEvent(eventName,remark)
    }
}